const inputText = document.querySelector('input')
const data = localStorage.getItem('data-item')
let dataArr = JSON.parse(data) ?? []
let finishedCounts = JSON.parse(localStorage.getItem('finishedcnt')) ?? 1  //已完成任务数
const ul = document.querySelector('ul')
const counts = document.querySelector('#counts')
const countsFinished = document.querySelector('.counts-finished')
const clearStorage = document.querySelector('#clear-storage') // 清理缓存按钮
// const dataArr = []

render() //初始化页面
inputText.addEventListener('keyup',function(e){ 
    if(e.key === 'Enter'){
    //    console.log(inputText.value)
    if(inputText.value.trim() === '') return alert('不能添加空白任务!')
    const item = inputText.value.trim()
    dataArr.push(item)
    localStorage.setItem('data-item',JSON.stringify(dataArr))
    render()
    inputText.value = ''
    }
})

ul.addEventListener('click',function(e){
    if(e.target.tagName === 'A'){
        dataArr.splice(e.target.dataset.id,1)
        finishedCounts++
        saveAll()
        render()
        // countsFinished.innerHTML = `已完成${finishedCounts++}件任务`
    }
})

//渲染页面函数
function render(){  
    counts.innerHTML = `${dataArr.length}`
    const liArr = dataArr.map(function(item,i){
        return`
        <li>${item}</li><a class='delete' data-id=${i}>删除</a>
        `
    })
    ul.innerHTML = liArr.join('')
}

//清理缓存
clearStorage.addEventListener('click',function(){  
    localStorage.clear()
    dataArr = []
    finishedCounts = 0
    render()
})     

//保存数据函数
function saveAll() {   
    localStorage.setItem('finishedcnt',finishedCounts)
    localStorage.setItem('data-item',JSON.stringify(dataArr))
} 